package app.service.login;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import app.model.login.LoginUser;
import app.model.login.QrLoginModel;
import app.thread.ScanLoginThread;
import app.util.UUIDUtil;

@Service
public class QrLoginService {
	
	@Resource
	private ScanLoginThread scanLoginThread;
	
//	/**
//	 * 从缓存中移除待登录ID
//	 * @param key
//	 */
//	public void delOneScanQrMap(String key){
//		waitScanQrMap.remove(key);
//	}
//
	public Object initQrLogin() {
		String key = UUIDUtil.getUUID();
		scanLoginThread.setKey(key);
		return key;
	}
//	
//	/**
//	 * 二维码扫描成功后,将值存入
//	 * @param key
//	 */
//	public void afterScanLogin(String key){
//		String success = "success";
//		waitScanQrMap.put(key, success);
//	}
//
//	public Object getWaitScanQrMap(String key) {
//		return waitScanQrMap.get(key);
//	}

	/**
	 * 前端等待终端扫描二维码
	 * @param loginId
	 */
	public QrLoginModel waitingQrLogin(String loginId) {
//		ScanLoginThreadChild target = new ScanLoginThreadChild();
//		Thread thread = new Thread(target);
//		thread.start();
//		System.out.println(ScanLoginThreadChild.isFinish);
//		while(!ScanLoginThreadChild.isFinish){
//			System.out.println(ScanLoginThreadChild.isFinish);
//		}
//		System.out.println(ScanLoginThreadChild.isFinish);
		
		int i = 0;
		
		while(i<10){
			try {
				i++;
				Thread.sleep(1000);
				Object waitScanQrMap = scanLoginThread.getWaitScanQrMap(loginId);
				if(waitScanQrMap!=null && waitScanQrMap instanceof QrLoginModel){
					return (QrLoginModel)waitScanQrMap;
				}
			} catch (InterruptedException e) {
			}
		}
		return new QrLoginModel(false, null);
	}

	/**
	 * 终端扫描二维码
	 * @param loginId
	 */
	public void scanQrLogin(String loginId) {
		LoginUser user = new LoginUser();
		user.setUserName("张三");
		user.setPassword("123");
		QrLoginModel qrLoginModel = new QrLoginModel(false, user);
		scanLoginThread.setValue(loginId, qrLoginModel);
	}

	/**
	 * 终端确认二维码登录
	 * @param loginId
	 */
	public void confirmQrLogin(String loginId) {
		Object waitScanQrMap = scanLoginThread.getWaitScanQrMap(loginId);
		if(waitScanQrMap!=null && waitScanQrMap instanceof QrLoginModel){
			QrLoginModel qrLoginModel = (QrLoginModel)waitScanQrMap;
			qrLoginModel.setAllowLogin(true);
			scanLoginThread.setValue(loginId, qrLoginModel);
		}
	}

}
